package com.guava.collection;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * LoadingCacheTester--GuavaTest
 *
 * @author: Jovi
 * @createTime: 2018-05-08 16:34
 **/
public class LoadingCacheTester {

    public static void main(String[] args) {

        LoadingCache employeeCache = CacheBuilder.newBuilder()
                .maximumSize(4)//最大缓存记录数
                .expireAfterAccess(10, TimeUnit.MINUTES)//缓存到期时间
                .build(new CacheLoader() {
                    public Object load(Object empId) throws Exception {
                        return getFromDatabase(empId.toString());
                    }
                });

        try {
            System.out.println("Invocation #1");
            System.out.println(employeeCache.get("100"));
            System.out.println(employeeCache.get("103"));
            System.out.println(employeeCache.get("110"));
            //second invocation, data will be returned from cache
            System.out.println("Invocation #2");
            System.out.println(employeeCache.get("100"));
            System.out.println(employeeCache.get("103"));
            System.out.println(employeeCache.get("110"));
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static Employee getFromDatabase(String empId) {
        Employee e1 = new Employee("Mahesh", "Finance", "100");
        Employee e2 = new Employee("Rohan", "IT", "103");
        Employee e3 = new Employee("Sohan", "Admin", "110");

        Map<String,Employee> database = new HashMap();
        database.put("100", e1);
        database.put("103", e2);
        database.put("110", e3);
        System.out.println("Database hit for" + empId);
        return database.get(empId);
    }

}



@AllArgsConstructor
@Data
class Employee {


    String name;
    String dept;
    String empId;
}
